package com.jsgt.greekfire.ui.entrust

import android.text.InputFilter
import android.text.TextUtils
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.LogUtils
import com.fhx.core.utils.ToastUtils
import com.google.gson.Gson
import com.google.protobuf.ByteString
import com.jsgt.greekfire.ENTRUST_NUM
import com.jsgt.greekfire.R
import com.jsgt.greekfire.common.util.DecimalDigitsInputFilter
import com.jsgt.greekfire.common.util.MD5Util
import com.jsgt.greekfire.common.util.UtilsBigDecimal
import com.jsgt.greekfire.dao.model.IdentityBean
import com.jsgt.greekfire.dao.model.IdentityWallet
import com.jsgt.greekfire.dao.viewmodel.WalletViewModel
import com.jsgt.greekfire.event.EntrustEvent
import com.jsgt.greekfire.ui.dialog.InputDialogUtil
import com.jsgt.greekfire.viewmodel.EntrustViewModel
import com.jsgt.greekfire.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.activity_add_entrust.*
import org.altoro.common.crypto.Sha256Sm3Hash
import org.altoro.common.crypto.SignUtils
import org.bouncycastle.util.encoders.Hex
import org.greenrobot.eventbus.EventBus
import java.math.BigDecimal
import java.math.BigInteger


class AddEntrustActivity : BaseActivity() {
    var node: String? = null
    var account_address: String? = null
    var entrust_address: String? = null
    private var identityBean: IdentityBean? = null

    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(this).get(UserViewModel::class.java)
    }
    private val walletViewModel: WalletViewModel by lazy {
        ViewModelProvider(this).get(WalletViewModel::class.java)
    }
    private val entrustViewModel: EntrustViewModel by lazy {
        ViewModelProvider(this).get(EntrustViewModel::class.java)
    }
    private var wallet: IdentityWallet? = null

    override fun needFitsSystemWindows(): Boolean {
        return false
    }

    override fun getLayoutId(): Int = R.layout.activity_add_entrust

    override fun main() {
        setStatusBar(R.color.transparent, false, R.color.white)
        title = getString(R.string.add_entrust)
        node = intent.getStringExtra("node");
        account_address = intent.getStringExtra("account_address");
        entrust_address = intent.getStringExtra("entrust_address");
        if (!TextUtils.isEmpty(node)) {
            tvEntrustNum.text = node;
        }
        if (!TextUtils.isEmpty(account_address)) {
            tvAccountAddress.text = entrust_address;
        }
        if (!TextUtils.isEmpty(entrust_address)) {
            tvEntrustAddress.text = account_address;
        }
        etEntrustAmount?.setFilters(arrayOf<InputFilter>(DecimalDigitsInputFilter(6)))
        walletViewModel.getSelectWallet()?.observe(this, Observer {
            if (it != null && it.isNotEmpty()) {
                wallet = it[0]
                userViewModel.getAccount(wallet?.address!!, "true")
                walletViewModel.getIdentity(wallet!!.identityId)?.observe(this, Observer { it1->
                    if (it1 != null) {
                        identityBean = it1
                    }
                })
            }
        })
        entrustViewModel.broadcasttransactionListData.observe(this, Observer {
            showProgress(false)
            if (it != null) {
                if (!TextUtils.isEmpty(it.txid)) {
                    EventBus.getDefault().post(EntrustEvent(""))
                    finish()
                }
            }
        })

        entrustViewModel.delegateaccountListData.observe(this, Observer {
            if (it != null && !TextUtils.isEmpty(it.raw_data_hex)) {
                try {
                val cryptoEngine = SignUtils.fromPrivate(Hex.decode(BigInteger(identityBean?.getPriKeyByAES()).toString(16)), true)
                val rawData = Sha256Sm3Hash.of(Hex.decode(it.raw_data_hex))
                val sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine.signHash(rawData.bytes)))
                val signature = Hex.toHexString(sig.toByteArray())
                it.signature = signature
                var data = Gson()
                entrustViewModel.broadcasttransaction(data.toJson(it))
            /*    var privateKey = YTWalletUtils.getPrivateKey(identityBean?.getMnemonicByAES())
                val rawData = Sha256Sm3Hash.of(Hex.decode(it.raw_data_hex))
                val sig = ByteString.copyFrom(privateKey.Base64toBytes(privateKey.signHash(rawData.bytes)))
                val signature = Hex.toHexString(sig.toByteArray())
                it.signature = signature
                var data = Gson()
                entrustViewModel.broadcasttransaction(data.toJson(it))*/
                        } catch (e: Exception) {
                   LogUtils.error(e.message)
                    e.printStackTrace()
                }
            }

        })
        userViewModel.getAccountLiveData.observe(this, Observer {
            if (it != null) {
                if (it.delegate != null && it.delegate!!.size > 0) {
                    for (delegateBean in it.delegate!!) {
                        if (delegateBean.delegate_address!!.equals(tvEntrustAddress.text.toString().trim())){
                            if (!TextUtils.isEmpty(delegateBean!!.delegate_count)) {
                                var div = UtilsBigDecimal.divZero(delegateBean!!.delegate_count!!, ENTRUST_NUM)
                                etEntrustAmount.setText(BigDecimal(div.toString()).stripTrailingZeros().toPlainString())
                            }
                        }
                    }
                }
                if (!TextUtils.isEmpty(it.balance)) {
                    var div = UtilsBigDecimal.div(it.balance!!, ENTRUST_NUM)
                    tvAvailableBalances.text = div.toString();
                } else {
                    tvAvailableBalances.text = "0";
                }
            }
        })
        entrustViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
            ToastUtils.show(it.toString())
        })

        btnAffirm.setOnClickListener {
            var entrustAmount = etEntrustAmount.text.toString().trim()
            if (!TextUtils.isEmpty(etEntrustAmount.text.toString().trim())) {
                if(entrustAmount.toDouble()>tvAvailableBalances.text.toString().trim().toDouble()){
                    ToastUtils.show(R.string.transfer_over_balance)
                    return@setOnClickListener
                }
                if (etEntrustAmount.text.toString().trim().toDouble() >= 10000) {
                    InputDialogUtil.showInputDialog(
                        this,
                        getString(R.string.pool_join_password_input),
                        getString(R.string.pool_join_password_input)
                    ) {
                        if (!TextUtils.isEmpty(it)) {
                            if (identityBean != null && !TextUtils.isEmpty(identityBean?.password)) {
                                if (MD5Util.getMD5(it) == identityBean?.password) {
                                    var div = UtilsBigDecimal.mul(entrustAmount, ENTRUST_NUM, 0)
                                    //  ToastUtils.show("加入委托")
                                    showProgress(true);
                                    entrustViewModel.delegateaccount(wallet?.address!!, account_address!!, div!!.toBigInteger(), "true")
                                    LogUtils.error(div);
                                } else {
                                    showToast(getString(R.string.pwd_error))
                                }

                            }
                        } else {
                            ToastUtils.show(getString(R.string.pool_join_password_input))
                        }
                    }
                } else {
                    ToastUtils.show(getString(R.string.entrust_num_hint1))
                }
            } else {
                ToastUtils.show(getString(R.string.entrust_num_hint))
            }
        }
    }

    override fun onResume() {
        super.onResume()
    }
}